/*
 * Copyright 2020-2025 the original author or authors.
 * You cannot use this file unless authorized by the author.
 */
package org.ipig.commons.helper;

import org.ipig.constants.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.exec.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Command Helper
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id: CommandHelper.java 3 2020-01-21 09:36:33Z ts <comchnts@163.com> $$
 * @since 1.0
 */
@Slf4j
public class CommandHelper {

    /**
     * exec Command
     *
     * @param command
     * @param timeout
     * @param absolutePathFileName
     * @return
     */
    public static ResultStatus execCommand(final String command, final long timeout, final String absolutePathFileName) {
        ResultStatus resultStatus = ResultStatus.SUCCESS;
        FileOutputStream fileOutputStream = null;
        AssertHelper.hasText(command, "please enter a valid command");
        try {
            CommandLine cmdLine = CommandLine.parse(command);// 命令行
            DefaultExecutor executor = new DefaultExecutor();// 创建执行器
            executor.setExitValue(1);
            ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);// 超时终止
            executor.setWatchdog(watchdog);
            if (StringUtils.isNotBlank(absolutePathFileName)) {
                File file = new File(absolutePathFileName);
//                FileUtils.writeStringToFile(file,command, StandardCharsets.UTF_8);
                // 重定向stdout和stderr到文件
                fileOutputStream = new FileOutputStream(file);
                PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(fileOutputStream);
                executor.setStreamHandler(pumpStreamHandler);
            }
            DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
            executor.execute(cmdLine, handler);
            handler.waitFor();//命令执行返回前一直阻塞
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            e.printStackTrace();
            resultStatus = ResultStatus.FAILURE;
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultStatus;
    }
}
